/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package it.polimi.deib.se2.meteocal.business.boundary;

import it.polimi.deib.se2.meteocal.business.entity.Event;
import it.polimi.deib.se2.meteocal.business.entity.Invitation;
import it.polimi.deib.se2.meteocal.business.entity.User;
import java.security.Principal;
import java.util.List;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

@Stateless
public class InvitationManager {
    
    @PersistenceContext
            EntityManager em;
    
    @Inject
            Principal principal;
    
    public void save(Invitation invitation) {
        em.persist(invitation);
    }
    
    public void update(Invitation invitation){
        em.merge(invitation);
        
    }
    
    public void remove(Invitation invitation){
        em.remove(em.merge(invitation));
    }
    
    public Invitation find(Long id) {
        return em.find(Invitation.class, id);
    }
    
    public List<Invitation> getInvitations(Event event) {
        Query q = em.createNativeQuery("SELECT * FROM meteocaldb.INVITATIONS WHERE referingEvent=\""+event.getId()+"\"",Invitation.class);
        return q.getResultList();
    }
    
    public boolean getPendingInvitationsByEventAndUser(Event event, User user) {
        Invitation i = getInvitationByEventAndUser(event, user);
        if(i==null)
            return false;
        else
            return (getInvitationByEventAndUser(event, user).isStatus() == false);
    }
    
    public Invitation getInvitationByEventAndUser(Event event, User user) {
        try{
            return (Invitation)em.createNativeQuery("SELECT * FROM meteocaldb.INVITATIONS WHERE (referingEvent=\""+event.getId()+"\" AND userInvited=\""+user.getEmail()+"\")",Invitation.class).getSingleResult();
        } catch (NoResultException e) {
            return null;
        }
    }
    
    public List<Invitation> getInvitationsAccepted(Event event) {
        Query q = em.createNativeQuery("SELECT * FROM meteocaldb.INVITATIONS WHERE referingEvent=\""+event.getId()+"\" AND STATUS=1",Invitation.class);
        return q.getResultList();
    }
}